package cool.tianyou.blue.bird.common.tool;

import cool.tianyou.blue.bird.common.model.po.LoginUser;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Liutianyou
 * @date 2021/7/31 11:31 上午
 */
public class LocalCache {

  public final ConcurrentHashMap<String, LoginUser> userCache = new ConcurrentHashMap<>();

  public void put(String token, LoginUser user) {
    userCache.put(token, user);
  }

  public Optional<LoginUser> get(String token) {
    if (token == null) {
      return Optional.empty();
    }
    LoginUser user = userCache.get(token);
    return Optional.ofNullable(user);
  }

  public void removeByDeviceId(Integer userId, Integer deviceId) {
    String token = null;
    for (String key : userCache.keySet()) {
      LoginUser value = userCache.get(key);
      if (Objects.equals(value.getUserId(), userId) && Objects
          .equals(deviceId, value.getDeviceId())) {
        token = key;
        break;
      }
    }
    if (token != null) {
      userCache.remove(token);
    }
  }

  public List<LoginUser> allUsers() {
    return new ArrayList<>(userCache.values());
  }


  /**
   * 更新缓存的设备别名
   *
   * @param deviceId 设备id
   * @param alias    别名
   */
  public void updateDeviceAlias(Integer deviceId, String alias) {
    for (LoginUser value : userCache.values()) {
      if (Objects.equals(deviceId, value.getDeviceId())) {
        value.setAlias(alias);
      }
    }
  }
}
